// src/hooks/useAiApi.ts
import { ref } from 'vue';

export const useAiApi = () => {
  const chatMessages = ref<{ sender: string; content: string }[]>([]);
  const isLoading = ref(false);

  const callAiApi = async (userMessage: string) => {
    const apiKey = "bce-v3/ALTAK-mpmEA0UbCHXFOUohK8jju/207e2c82611d0ed260e8878d28d00fcdd99bb0b9";
    const base_url = "https://qianfan.baidubce.com/v2/chat/completions";
    
    if (!userMessage.trim()) return;  // 如果消息为空，则直接返回

    // 构造历史对话
    const messages = chatMessages.value.map(msg => ({
      role: msg.sender === "user" ? "user" : "assistant", // 使用 user 或 assistant 角色
      content: msg.content
    }));

    // 添加当前用户消息
    messages.push({ role: "user", content: userMessage });

    const body = {
      model: "ernie-3.5-8k",
      messages: messages,
    };

    console.log('API 请求体:', JSON.stringify(body));  // 打印请求体

    isLoading.value = true;  // 开始请求

    try {
      const resp = await fetch(base_url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${apiKey}`,
        },
        body: JSON.stringify(body),
      });

      if (!resp.ok) {
        const errorText = await resp.text();
        console.error(`AI 请求失败: ${resp.status} ${resp.statusText}`, errorText);
        return;
      }

      const jsonResponse = await resp.json();  // 获取 JSON 响应内容
      console.log('AI 返回的内容:', jsonResponse); // 打印整个返回对象

      const aiResponse = jsonResponse.choices[0]?.message?.content || ''; // 访问返回的消息内容
      if (aiResponse) {
        chatMessages.value.push({ sender: "assistant", content: aiResponse });
      }

    } catch (error) {
      console.error("AI 请求失败:", error);
    } finally {
      isLoading.value = false;  // 请求结束
    }
  };

  return {
    chatMessages,
    isLoading,
    callAiApi,
  };
};
